﻿using System;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using eLearning.Model;
using eLearning.Util;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Newtonsoft.Json;
using Microsoft.Phone.Tasks;

namespace eLearning.DosenView
{
    public partial class ResourcesPage : PhoneApplicationPage
    {
        private DetailMatkul detMatkul;
        private Resources resource;

        public ResourcesPage()
        {
            InitializeComponent();
            detMatkul = null;
            this.Loaded += new RoutedEventHandler(DataContextPage_Loaded);
        }

        private void DataContextPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (PhoneApplicationService.Current.State.ContainsKey(Config.DETMATKUL))
            {
                detMatkul = (DetailMatkul)PhoneApplicationService.Current.State[Config.DETMATKUL];
            }
            if (detMatkul == null)
            {
                detMatkul = new DetailMatkul();
                detMatkul.Creator = (Dosen)SavedUser.Instance.User.ConvertUser();
            }
            LoadResources();
        }

        private void LoadResources()
        {
            pivotResources.SelectedIndex = 0;
            listResources.ItemsSource = null;
            resource = null;

            string url = string.Format("{0}&{1}", Config.Instance.RESOURCES_SERVICE_URL() + Config.VIEW_ACTION_KEY, Guid.NewGuid().ToString());
            string json = JsonConvert.SerializeObject(detMatkul);

            Uri uri = new Uri(url, UriKind.Absolute);
            WebClient webClient = new WebClient();

            webClient.Encoding = Encoding.UTF8;
            webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
            webClient.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

            webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(listResources_UploadStringCompleted);
            try
            {
                webClient.UploadStringAsync(uri, "POST", json);
            }
            catch (Exception) { }
        }

        private void listResources_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            if (e.Error != null)
                return;

            try
            {
                ResourcesList list = JsonConvert.DeserializeObject<ResourcesList>(e.Result);
                if (list.Count > 0)
                {
                    listResources.ItemsSource = list;
                }
                else
                {
                    listResources.ItemsSource = null;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void DeleteCurrentResource()
        {
            string json = null, url = null;

            if (resource != null)
            {
                url = Config.Instance.RESOURCES_SERVICE_URL() + Config.DELETE_ACTION_KEY;
                json = JsonConvert.SerializeObject(resource);

                Uri uri = new Uri(url, UriKind.Absolute);
                WebClient client = new WebClient();

                client.Encoding = Encoding.UTF8;
                client.Headers[HttpRequestHeader.ContentType] = "application/json";
                client.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

                client.UploadStringCompleted += new UploadStringCompletedEventHandler(deleteResource_UploadStringCompleted);

                try
                {
                    client.UploadStringAsync(uri, "POST", json);
                }
                catch (Exception) { }
            }
        }

        private void deleteResource_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Cancelled && e.Error != null)
                    return;

                MessageBox.Show("Message : " + e.Result);
                if (e.Result.Contains("Success"))
                    LoadResources();

            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR : " + ex.Message);
            }
        }

        private void listResources_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                resource = (Resources)e.AddedItems[0];
                ((ListBox)sender).SelectedIndex = -1;

                if (resource != null)
                {
                    pivotResources.SelectedIndex = 1;
                    textBoxCreated.Text = resource.Created.ToString("dd/MM/yyyy");
                    textBoxJudul.Text = resource.Judul;
                    textBoxLink.Text = resource.Link;
                }
            }
        }

        private void pivotResources_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (resource == null)
            {
                textBoxCreated.Text = "";
                textBoxJudul.Text = "";
                textBoxLink.Text = "";
            }

            if (pivotResources.SelectedIndex == 1 && resource != null)
            {
                ((ApplicationBarIconButton)ApplicationBar.Buttons[1]).IsEnabled = true;
                ((ApplicationBarIconButton)ApplicationBar.Buttons[2]).IsEnabled = true;
            }
            else
            {
                ((ApplicationBarIconButton)ApplicationBar.Buttons[1]).IsEnabled = false;
                ((ApplicationBarIconButton)ApplicationBar.Buttons[2]).IsEnabled = false;
            }

        }

        private void addButton_Click(object sender, EventArgs e)
        {
            Utility.GotoPage(this, "/View/Dosen/ResourcesFormPage.xaml");

            Resources res = new Resources();
            res.DetMatkul = detMatkul;
            PhoneApplicationService.Current.State[Config.RESOURCES] = res;
        }

        private void editButton_Click(object sender, EventArgs e)
        {
            Utility.GotoPage(this, "/View/Dosen/ResourcesFormPage.xaml");
            PhoneApplicationService.Current.State[Config.RESOURCES] = resource;
        }

        private void removeButton_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Remove " + resource.Judul + "?", "", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                DeleteCurrentResource();
        }

        private void refreshButton_Click(object sender, EventArgs e)
        {
            LoadResources();
        }

        private void TextBlock_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            try
            {
                var task = new Microsoft.Phone.Tasks.WebBrowserTask
                {
                    Uri = new Uri(textBoxLink.Text.Contains("http://") ? textBoxLink.Text : "http://" + textBoxLink.Text)
                };

                task.Show();
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
        }
    }
}